<template>
  <div>
    <div v-if="!enterExercise">
      <el-select v-model="selectGameType" placeholder="对局类型" size="mini" filterable style="width: 100px" class="firstLine"
                 clearable>
        <el-option
            v-for="item in selectGameTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="selectType" placeholder="习题类型" size="mini" filterable style="width: 100px" class="firstLine"
                 clearable>
        <el-option
            v-for="item in selectTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
          v-model="selectDate"
          align="right"
          type="date"
          placeholder="~至今"
          :picker-options="pickerOptions"
          size="mini"
          style="width:130px"
          clearable
      >
      </el-date-picker>

      <el-select v-model="selectAnalyze" placeholder="分析" size="mini" style="width: 90px" class="firstLine"
                 clearable>
        <el-option
            v-for="item in analyzeSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="selectLearn" placeholder="学习" size="mini" style="width: 90px" class="firstLine" 
                 clearable>
        <el-option
            v-for="item in learnSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="selectDisabled" placeholder="禁用" size="mini" style="width: 90px" class="firstLine"
                 clearable>
        <el-option
            v-for="item in disabledSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button size="mini" type="primary" @click="searchByCond" style="margin-left: 10px"  class="firstLine" :loading=analyzeDisabled >查询</el-button>
      <el-tooltip class="item" effect="dark" content="以筛选的条件随机抽取习题" placement="top">
        <el-button size="mini" type="success" @click="startLearn" style="margin-left: 10px"  class="firstLine" :loading=analyzeDisabled >练习</el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="可批量禁用如超快棋或者多年前产生的错题" placement="top">
        <el-button size="mini" type="danger" @click="disabledModal=true" style="margin-left: 10px"  class="firstLine" :loading=analyzeDisabled >禁用</el-button>
      </el-tooltip>

      <el-tooltip class="item" effect="dark" content="以更高的精度重新分析习题" placement="top">
        <el-button size="mini" type="danger" @click="analyzeExercise()" style="float: right;"  class="firstLine" :loading="analyzeNotDone">{{!isAnalyzeAll ? '精确分析' : '结束分析'}}</el-button>
      </el-tooltip>



      <el-table :data="exerciseData" stripe border :height="630" style="margin-top: 10px">
        <el-table-column
            prop="index" :show-overflow-tooltip="true"
            label="序号"
            type="index"
            width="50">
        </el-table-column>
        <el-table-column
            prop="gameType" :show-overflow-tooltip="true"
            label="赛事"
            width="100">
        </el-table-column>

        <el-table-column
            prop="white" :show-overflow-tooltip="true"
            label="白方"
            width="120">
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true"
                         prop="black"
                         label="黑方"
                         width="120">
        </el-table-column>
        <el-table-column
            prop="type" :show-overflow-tooltip="true"
            label="类型"
            width="80">
        </el-table-column>
        <el-table-column
            prop="badMove" :show-overflow-tooltip="true"
            label="错着"
            width="100">
        </el-table-column>
        <el-table-column
            prop="correctMove" :show-overflow-tooltip="true"
            label="正着"
            width="100">
        </el-table-column>
        <el-table-column
            prop="value" :show-overflow-tooltip="true"
            label="分差"
            width="80">
        </el-table-column>
        <el-table-column
            prop="analyzed"
            label="分析"
            width="50">
        </el-table-column>
        <el-table-column
            prop="learn"
            label="学习"
            width="50">
        </el-table-column>
        <el-table-column
            prop="disabled"
            label="禁用"
            width="50">
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true"
                         prop="gameDate"
                         label="对局时间"
                         width="170">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
        >
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="learnExercise(scope.row)" >查看</el-button>
            <el-button type="danger" size="mini" @click="disableExercise(scope.row)"  :disabled="analyzeDisabled">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="float: right; margin: 5px 20px 5px 5px;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 50, 100]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="exerciseCount">
      </el-pagination>
      <!--    导入fen的对话框-->
      <el-dialog
          :visible.sync="disabledModal"
          title="处理数据"
          width="800px"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
      >
        <h3>对当前筛选的习题统一处理</h3>
        <el-switch
            style="display: block"
            v-model="disableStatus"
            active-color="#13ce66"
            inactive-color="#ff4949"
            inactive-text="全部禁用"
            active-text="全部启用">
        </el-switch>
        <br>
        <el-button @click="disabledModal = false" size="mini">取消</el-button>
        <el-button type="primary" @click="disableManyExercise" size="mini">确定</el-button>
      </el-dialog>

    </div>
    <div v-if="enterExercise">
      <ExerciseBoard
          :data="boardData"
          :cond="exerciseCond"
          :type="exerciseType"
      >
      </ExerciseBoard>
    </div>
  </div>
</template>

<script>

import {invoke} from "@/lib/utils";
import Chessmate from "@/lib/chessmate";
import path from "path";
import fs from "fs";
import Sqlite from "@/lib/sqlite";
import Database from "@/lib/database";
import moment from "moment/moment";
import ExerciseBoard from "@/components/user/ExerciseBoard.vue";
import emitvue from "@/lib/emitvue";

export default {
  name: "exercise",
  data() {
    return {
      isDev: false,

      enterExercise: false,
      // 页码和大小
      currentPage: 1,
      currentSize: 20,
      exerciseData: [],
      exerciseCount: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: '今年',
            onClick(picker) {
              picker.$emit('pick', moment().startOf('years').valueOf());
            }
          },
          {
            text: '去年',
            onClick(picker) {
              picker.$emit('pick', moment().startOf('years').add(-1, 'years').valueOf());
            }
          },
          {
            text: '本月',
            onClick(picker) {
              picker.$emit('pick', moment().startOf('months').valueOf());
            }
          },
          {
            text: '上个月',
            onClick(picker) {

              picker.$emit('pick', moment().startOf('months').add(-1, 'months').valueOf());
            }
          },
          {
            text: '本周',
            onClick(picker) {
              picker.$emit('pick', moment().startOf('isoWeeks').valueOf());
            }
          },
        ]
      },
      analyzeSelect: [
        {label: '已分析', value: 1},
        {label: '未分析', value: 0},
      ],
      learnSelect: [
        {label: '已学习', value: 1},
        {label: '未学习', value: 0},
      ],
      disabledSelect: [
        {label: '已禁用', value: 1},
        {label: '未禁用', value: 0},
      ],
      selectDisabled: '',
      selectLearn: '',
      selectAnalyze: '',
      selectDate: '',
      selectType: '',
      selectTypeList: [
        {label: '败着', value: "败着"},
        {label: '错着', value: "错着"},
        {label: '不精确', value: "不精确"},
      ],
      selectGameType: '',
      selectGameTypeList: [],
      // 禁用的确认对话框
      disabledModal: false,
      disableStatus: true,
      boardData: null,
      allExercise: [],
      exerciseCond: null,
      exerciseType: '',
      isAnalyzeAll: false,
      analyzeDisabled: false,
      analyzeNotDone: false,
    }
  },
  methods: {
    async getSetting() {
      this.appPath = await invoke('getCurrentPath', null)
      let config = await invoke('get', {name: 'setting', type: 'database'})
      this.lichessUserName = config.lichessUserName
      this.pluginPath = config.pluginPath
      this.dbFolderPath = config.dbFolderPath
      const chessConfig = {
        path: config.enginePath,
        analyzeSpeed: config.analyzeSpeed,
        blunderThreshold: config.blunderThreshold,
        mistakeThreshold: config.mistakeThreshold,
      }
      this.exportFilePath = config.exportFilePath || './'
      await Chessmate.init(chessConfig)
    },
    // 检查user.db是否存在于用户目录 不存在则复制
    async checkUserDb() {
      const userCachePath = await invoke('getUserDataPath', null)
      const userDbPath = path.join(userCachePath, './chessmate/user.db')
      const dbDir = path.join(userCachePath, './chessmate')
      const backUpDBPath = path.join(this.dbFolderPath, './user.db')
      if (!fs.existsSync(backUpDBPath)) {
        return this.$notify({duration: 1000, title: '通知', message: "备份数据未找到，请联系开发者", type: 'error'})
      }
      // 理论上这个文件夹只要程序打开就一定存在
      if (!fs.existsSync(dbDir)) {
        fs.mkdirSync(dbDir)
      }
      if (!fs.existsSync(userDbPath)) {
        fs.copyFileSync(backUpDBPath, userDbPath)
        this.$notify({duration: 1000, title: '通知', message: `已成功初始化用户数据`, type: 'success'})
      }
      await Sqlite.connectUser(userDbPath)
      await this.getExerciseData()
      await this.getDistinctExerciseType()
    },
    async getDistinctExerciseType() {
      const data = await Database.getDistinctTypeFromExercise()
      this.selectGameTypeList = []
      for (const item of data) {
        this.selectGameTypeList.push({label: item.gameType, value: item.gameType})
      }
    },
    // 转换数据库的返参
    parseExerciseData(res) {
      for (const item of res.data) {
        item.gameDate = moment(Number(item.gameDate)).format('YYYY-MM-DD HH:mm:ss')
        item.analyzed = item.analyzed === 0 ? '否' : '是'
        item.learn = item.learn === 0 ? '否' : '是'
        item.disabled = item.disabled === 0 ? '否' : '是'
      }
      this.exerciseData = res.data
      this.exerciseCount = res.count[0]?.count || 0
    },
    async handleCurrentChange(data) {
      if (this.currentPage === data) return
      this.currentPage = data
      await this.getExerciseDataByCond(false)
    },
    async handleSizeChange(data) {
      if (this.currentSize === data) return
      this.currentSize = data
      await this.getExerciseDataByCond(false)
    },
    // 按条件查询
    async getExerciseDataByCond(message=true) {
      if (this.selectDate) {
        this.selectDate = moment(this.selectDate).valueOf()
      }
      const cond = {
        type: this.selectType,
        order: this.order,
        orderByKey: this.orderByKey,
        gameDate: this.selectDate,
        userName: this.lichessUserName,
        analyze: this.selectAnalyze,
        learn: this.selectLearn,
        disabled: this.selectDisabled,
        gameType: this.selectGameType,
      }
      await this.getExerciseData(cond)
      if (message) this.$notify({duration: 1000, title: '通知', message: '已成功获取数据', type: 'success'})

    },
    async getExerciseData(cond = null) {
      const res = await Database.getExerciseByPage(this.currentSize, (this.currentPage - 1) * this.currentSize, cond)
      this.parseExerciseData(res)
    },
    // 按条件查询的按钮
    async searchByCond() {
      // 先把分页重置
      this.currentSize = 20
      this.currentPage = 1
      await this.getExerciseDataByCond()
    },
    // 学习错题
    async learnExercise(data) {
      console.log("data", data)
      this.boardData = data
      this.enterExercise = true
    },
    // 按规则做题
    async startLearn() {
      const cond = {
        type: this.selectType,
        order: this.order,
        orderByKey: this.orderByKey,
        gameDate: this.selectDate,
        userName: this.lichessUserName,
        analyze: this.selectAnalyze,
        learn: this.selectLearn,
        disabled: this.selectDisabled,
        gameType: this.selectGameType,
      }
      this.exerciseCond = cond
      this.exerciseType = 'allExercise'
      this.enterExercise = true
    },
    // 分析错题
    async analyzeExercise() {
      const exerciseList = await Database.getExerciseForLearn({analyze: 0, order: 'desc', disabled: 0})
      const count = exerciseList.data?.length

      if (!count) return this.$notify({duration: 1000, title: '通知', message: `没有需要分析的习题`, type: 'warning'})
      this.isAnalyzeAll = !this.isAnalyzeAll
      if (!this.isAnalyzeAll) {
        const count = Chessmate.exitAnalyze()
        this.$notify({duration: 1000, title: '通知', message: `已经分析了约${count}个习题，删除了${Chessmate.getAnalyzeDelete()}个习题，请等待最后一个习题分析完成再开始自动分析`, type: 'success'})
        this.analyzeNotDone = true
      } else {
        emitvue.$emit('beginAnalyze')
        this.analyzeDisabled = true
        this.$notify({duration: 1000, title: '通知', message: `正在以精确的分析精度进行自动分析`, type: 'warning'})

        await Chessmate.analyzeExercise()

      }
    },
    async disableExercise(data) {
      await Database.disableExercise(data.fenHash, data.moveNum)
      this.$notify({duration: 1000, title: '通知', message: `处理成功`, type: 'success'})
      await this.getExerciseDataByCond(false)
    },
    // 禁用多个题目
    async disableManyExercise() {
      console.log("this.disableStatus", this.disableStatus)
      const cond = {
        type: this.selectType,
        gameType: this.selectGameType,
        gameDate: this.selectDate,
        userName: this.lichessUserName,
        analyze: this.selectAnalyze,
        learn: this.selectLearn,
        disabled: this.selectDisabled,
        // 0还是1根据开关处理，不要搞反了
        disableStatus: this.disableStatus === true ? 0 : 1,
      }
      const count = await Database.disabledExerciseByCond(cond)
      if (count === -1) return       this.$notify({duration: 1000, title: '通知', message: `请先选择筛选条件，再操作习题数据`, type: 'warning'})
      this.$notify({duration: 1000, title: '通知', message: `已经处理了${count}个习题`, type: 'success'})
      this.disabledModal = false
      await this.getExerciseDataByCond(false)
    }
  },
  async mounted() {
    await this.getSetting()
    await this.checkUserDb()
    this.isDev = location.protocol.indexOf('http') !== -1
    // 如果是开发模式，默认走老板键
    const isHome = await invoke('isHome', null)
    if (isHome === 'true' || isHome === true) {

    } else {
      this.isBoss = this.isDev
    }
    emitvue.$on('back2ExerciseList', async ()=>{
      this.enterExercise = false
      this.exerciseCond = null
      this.exerciseType = ''
      await this.getExerciseDataByCond(false)
    })
    emitvue.$on("analyzeStop", async ()=>{
      console.log("接收到分析完成的通知")
      if (this.analyzeDisabled === false) return
      this.analyzeDisabled = false
      emitvue.$emit('exitAnalyze')
    })
    emitvue.$on("analyzeRealStop", async () => {
      console.log("接收全部分析完成的通知")
      this.analyzeDisabled = false
      this.isAnalyzeAll = false
      emitvue.$emit('exitAnalyze')
    })
  },
  watch: {
    async analyzeDisabled() {
      if (this.analyzeDisabled === false) {
        this.$message({message: '分析已全部完成', type: 'success', duration: 1000})
        this.analyzeNotDone = false
        await this.getExerciseDataByCond(false)
      }
    }
  },
  components: {
    ExerciseBoard
  },
}
</script>


<style scoped>

</style>